package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.List;

import Dao.StudentDao;
import Dao.jdbcTools;
import Model.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

@WebServlet("/updateok")
public class UpdateOk extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String sex = req.getParameter("sex");
        String age = req.getParameter("age");
        String major = req.getParameter("major");
        String time = req.getParameter("time");
        InputStream in = Resources.getResourceAsStream("config/mybatis-config.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        SqlSession sqlSession = factory.openSession();
        StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
        Student student = new Student();student.setId(Integer.valueOf(id));
        student.setName(name);student.setSex(sex);student.setAge(Integer.valueOf(age));
        student.setMajor(major);student.setTime(time);
        int update = studentDao.updateStudent(student);
        sqlSession.commit();
        // int update = jdbcTools.update1("update stuhhh set name=?,sex=?,age=?,major=?,time=? where id=?", name, sex, age, major, time, id);
        if (update>0){
            List<Student> list = studentDao.findAll();
            // List<Student> list = jdbcTools.selectall("select * from stuhhh", Student.class);
            req.setAttribute("list",list);
            req.getRequestDispatcher("showlist4.jsp").forward(req,resp);
        }
    }
}
